<template>
  <t-card :bordered="false">
    <div
      style="height: calc(100vh - 220px)"
    >
      <fc-designer class="my-designer" ref="designer" :config="designerConfig">
        <template #handle>
          <t-button size="small" theme="success" plain @click="handleSave">
            <Icon class="mr-5px" icon="ep:plus" />
            保存
          </t-button>
        </template>
      </fc-designer>
    </div>

         <!-- 自定义对话框 -->
    <custom-dialog 
      ref="customDialogRef" 
      v-slot="{ formData, readonly }" 
      :api-map="formCRUD" header="保存表单"
      :on-before-save-data="handleDialogSaveData"
     @request-success="handleDialogRequestSuccess" >
      
      <t-form-item  label="表单名" name="name" :rules="[
        { required: true, message: '请输入表单名' },
      ]" >
        <t-input 
          v-model:value="formData.name" 
          placeholder="请输入表单名" 
          clearable 
          :readonly="readonly" 
        />
      </t-form-item>
       <t-form-item label="状态" name="status" :rules="[
        { required: true, message: '请选择状态' },
      ]" >
        <t-select
            v-model:value="formData.status"
            :options="dictionaryStore.get('common_status','number')"
            clearable
            filterable
            placeholder=""
          />
      </t-form-item>
      <t-form-item  label="备注" name="remark"  >
        <t-textarea
          v-model:value="formData.remark" 
          placeholder="请输入备注" 
          clearable 
          :readonly="readonly" 
        />
      </t-form-item>
      
    </custom-dialog>

  </t-card>
</template>

<script lang="ts">
export default {
  name: 'FormEditor',
};
</script>

<script lang="ts" setup>
import dayjs from 'dayjs';
import { onMounted, reactive, ref, useTemplateRef } from 'vue';
import { DialogPlugin, MessagePlugin, TableCol } from 'tdesign-vue-next';
import { useRoute, useRouter } from 'vue-router';
import { formCRUD } from '@/api/bpm/form';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import FormCreate from '@/components/FormCreate/index.vue';
import { useDictionaryStore, useTabsRouterStore } from '@/store';
import { encodeConf, encodeFields, setConfAndFields } from '@/utils/form'
import { TRouterInfo } from '@/types/interface';
// route
const route = useRoute();
const router = useRouter();
// 字典仓库
const dictionaryStore = useDictionaryStore();
const formData = ref({
  name: '',
  status: 0,
  remark: ''
})
const formRules = reactive({
  name: [{ required: true, message: '表单名不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
// 表单设计器配置
const designerConfig = ref({
  switchType: [], // 是否可以切换组件类型,或者可以相互切换的字段
  autoActive: true, // 是否自动选中拖入的组件
  useTemplate: false, // 是否生成vue2语法的模板组件
  formOptions: {}, // 定义表单配置默认值
  fieldReadonly: false, // 配置field是否可以编辑
  hiddenDragMenu: false, // 隐藏拖拽操作按钮
  hiddenDragBtn: false, // 隐藏拖拽按钮
  hiddenMenu: [], // 隐藏部分菜单
  hiddenItem: [], // 隐藏部分组件
  hiddenItemConfig: {}, // 隐藏组件的部分配置项
  disabledItemConfig: {}, // 禁用组件的部分配置项
  showSaveBtn: false, // 是否显示保存按钮
  showConfig: true, // 是否显示右侧的配置界面
  showBaseForm: true, // 是否显示组件的基础配置表单
  showControl: true, // 是否显示组件联动
  showPropsForm: true, // 是否显示组件的属性配置表单
  showEventForm: true, // 是否显示组件的事件配置表单
  showValidateForm: true, // 是否显示组件的验证配置表单
  showFormConfig: true, // 是否显示表单配置
  showInputData: true, // 是否显示录入按钮
  showDevice: true, // 是否显示多端适配选项
  appendConfigData: [] // 定义渲染规则所需的formData
})
const designer = ref() // 表单设计器
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
/** 处理保存按钮 */
const handleSave = () => {
  if(formData.value.id) {
    handleOpenDialog('update',formData.value)
  } else {
    handleOpenDialog('create',formData.value)
  }
}
/** 初始化 **/
onMounted(async () => {
  // 场景一：新增表单
  const id = route.query.id as unknown as number
  if (!id) {
    return
  }

  
  // 场景二：修改表单
  const data = await formCRUD.get({id})
  formData.value = data
  setConfAndFields(designer, data.conf, data.fields)
})
// 对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  const tabsRouterStore = useTabsRouterStore();
  const currentRoute = router.currentRoute.value;
  
  // 查找当前路由在 tab 列表中的索引
  const currentTabIndex = tabsRouterStore.tabRouters.findIndex(
    (route: TRouterInfo) => route.path === currentRoute.path
  );
  
  // 如果找到当前路由的 tab，则关闭它
  if (currentTabIndex >= 0) {
    tabsRouterStore.subtractCurrentTabRouter({
      ...currentRoute,
      routeIdx: currentTabIndex
    });
  }
  router.push({ path: '/approve/form' })

};
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>)=>{
  console.log(params);
  
   params.conf = encodeConf(designer) // 表单配置
  params.fields = encodeFields(designer) // 表单字段
  

};
</script> 
<style>
.my-designer {
  ._fc-l,
  ._fc-m,
  ._fc-r {
    border-top: none;
  }
}
</style>